import { Text, View } from "@tarojs/components";
import { useEffect, useState } from "react";
import { AtIcon } from "taro-ui";
import Taro from "@tarojs/taro";
import "./index.scss";

type NavBarProps = {
    title?: string;
    needBackIcon?: boolean;
    backIconColor?: string;
    goBack?: () => void;
    titleColor?: string;
    updateNavBarHeight?: (navH: number) => void;
    navBackground?: string;
};

const NavBar = ({
    title,
    needBackIcon = true,
    backIconColor = "#000",
    goBack,
    titleColor = "#000",
    updateNavBarHeight,
    navBackground = "#FFF",
}: NavBarProps) => {
    const [navBarHeight, setNavBarHeight] = useState<number>(0);

    useEffect(() => {
        getNavHeight();
    }, []);

    useEffect(() => {
        if (updateNavBarHeight) {
            updateNavBarHeight(navBarHeight);
        }
    }, [navBarHeight]);

    function getNavHeight() {
        const menuButtonObject = Taro.getMenuButtonBoundingClientRect(); //获取胶囊对象
        const sysInfo = Taro.getSystemInfoSync(); // 获取设备系统对象
        const statusBarHeight = sysInfo.statusBarHeight; // 获取状态栏高度
        const menuBottomHeight = menuButtonObject.height; //获取胶囊顶部高度
        const menuBottomTop = menuButtonObject.top;
        // @ts-ignore
        const navBarH =
            statusBarHeight +
            menuBottomHeight +
            (menuBottomTop - statusBarHeight) * 2;
        setNavBarHeight(navBarH);
    }

    function goBackPage() {
        Taro.navigateBack({
            delta: 1,
        });
    }

    return (
        <View
            className="nav_custom_bar"
            style={{ height: ` ${navBarHeight}px`, background: navBackground }}
        >
            <AtIcon
                className={`nav_custom_bar_back ${needBackIcon ? "" : "hidden"}`}
                value="chevron-left"
                size="22"
                color={backIconColor}
                onClick={() => {
                    if (goBack) {
                        goBack();
                    } else {
                        goBackPage();
                    }
                }}
            />
            <Text
                className="nav_custom_bar_title"
                style={{ color: titleColor }}
            >
                {title}
            </Text>
            <View />
        </View>
    );
};

export default NavBar;

